import React, { useEffect } from 'react';
import { Modal, Form, Input, Upload, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

// eslint-disable-next-line no-unused-vars
const uploadProps = {
    name: 'file',
    action: 'https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188',
    headers: { authorization: 'authorization-text' },
    onChange(info) {
        if (info.file.status !== 'uploading') {
            // eslint-disable-next-line no-console
            console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
            message.success(`${info.file.name} file uploaded successfully`);
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} file upload failed.`);
        }
    },
    showUploadList: false,
};

const EditModal = ({
    open,
    setOpen,
    editData,
    onSubmit,
}) => {
    const [form] = Form.useForm();

    const handleSubmit = () => {
        const formData = form.getFieldsValue();
        onSubmit({
            title: formData.title,
            subTitle: formData.subTitle,
            img: formData.img?.[0]?.thumbUrl,
            id: editData.id,
        });
        setOpen(false);
    };

    useEffect(() => {
        if (open) {
            form.setFieldsValue({
                ...editData,
                ...editData.img && {
                    img: [{
                        name: 'img',
                        thumbUrl: editData.img,
                        response: { imgUrl: editData.img },
                    }],
                },
            });
        } else {
            form.resetFields();
        }
    }, [open]);

    return (
        <Modal
            title="编辑轮播图"
            open={open}
            onCancel={() => setOpen(false)}
            onOk={handleSubmit}
        >
            <Form
                form={form}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 14 }}
                layout="horizontal"
                style={{ maxWidth: 600 }}
            >
                <Form.Item
                    label="图片"
                    name="img"
                    valuePropName="fileList"
                    getValueFromEvent={(e) => e.fileList}
                >
                    <Upload action="/upload.do" listType="picture-card" maxCount={1}>
                        <div>
                            <PlusOutlined />
                            <div style={{ marginTop: 8 }}>Upload</div>
                        </div>
                    </Upload>
                </Form.Item>

                <Form.Item label="一级标题" name="title">
                    <Input />
                </Form.Item>

                <Form.Item label="二级标题" name="subTitle">
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default EditModal;
